package com.xhis.homenurse.tools;

import android.os.Environment;
import android.util.Log;

import com.xhis.homenurse.GLobalApp;

import java.io.File;
import java.io.FileOutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * Created by 张兵 on 2019/7/16.
 */
public class LogUtil
{
    private static String TAG = "LogUtil";
    private static SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd");
    private static SimpleDateFormat hourFormatter = new SimpleDateFormat("HH时");
    private static SimpleDateFormat timeFormatter = new SimpleDateFormat("HH:mm:ss");
    /**
     * 保存出入参日志
     * @param title
     * @param content
     */
    public static void saveLog(String title, String content){
        String path = GLobalApp.getSDCardPath();
        if(path==null)
            return;
        Date nowDate = new Date();
        String date = dateFormatter.format(nowDate);
        String time = hourFormatter.format(nowDate);
        String fileName = "Log-" + time + ".txt";
        String dirPath = path + "/xxhis/NurseWorkStation/Log/IO";
        //PDA终端日志文件保存7天，大于或等于7天的则删除
        try {
            Calendar c = Calendar.getInstance();
            c.setTime(dateFormatter.parse(date));
            Long currentTime = c.getTimeInMillis();//当前时间

            File file = new File(dirPath);
            Calendar c2 = Calendar.getInstance();

            if (file.exists()) {
                if (file != null) {
                    File[] files = file.listFiles();
                    for (File file2 : files) {//遍历log下的时间文件
                        c2.setTime(dateFormatter.parse(file2.getName()));
                        Long directoryTime = c2.getTimeInMillis();//文件创建时间
                        //604800000为7天的毫秒数
                        if (currentTime - directoryTime >= 604800000) {
                            deleteDir(file2.getPath());
                        }
                    }
                }
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        dirPath =dirPath+"/"+date+"/";
        content = "\n["+timeFormatter.format(nowDate)+" - "+title+"]:"+content;
        saveMessageToFile(dirPath,fileName,content);
    }

    /**
     * 保存字符串到制定文件夹
     * @param dirPath
     * @param fileName
     * @param content
     */
    private static void saveMessageToFile(String dirPath, String fileName,String content){
        try {
            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                File dir = new File(dirPath);
                if (!dir.exists()) {
                    dir.mkdirs();
                }
                FileOutputStream fos = new FileOutputStream(dirPath + fileName, true);
                fos.write(content.getBytes());
                fos.close();
            }
        } catch (Exception e) {
            Log.e(TAG, "an error occured while writing file...", e);
        }
    }

    /**
     * 删除文件夹和文件夹里面的文件
     */
    public static void deleteDir(final String pPath)
    {
        File dir = new File(pPath);
        deleteDirWihtFile(dir);
    }

    public static void deleteDirWihtFile(File dir)
    {
        if (dir == null || !dir.exists() || !dir.isDirectory())
            return;
        for (File file : dir.listFiles()) {
            if (file.isFile())
                file.delete(); // 删除所有文件
            else if (file.isDirectory())
                deleteDirWihtFile(file); // 递规的方式删除文件夹
        }
        dir.delete();// 删除目录本身
    }
}
